const app = getApp();

Page({
  data: {
    activeTab: 0,
    orderList: [],
    loading: false,
    page: 1,
    totalPages: 1,
    statusCounts: {},
    queryParams: {
      role: 'all',
      page: 1,
      limit: 10,
      sort: 'createdAt',
      order: 'desc'
    },
    windowHeight: 0,
    tabsHeight: 44,
    needsRefresh: false, // 用于从评价页返回时刷新
  },

  onLoad() {
    // 获取设备信息
    const systemInfo = wx.getSystemInfoSync();
    this.setData({
      windowHeight: systemInfo.windowHeight
    });

    this.loadOrders();
  },

  // 切换标签页
  async onTabChange(event) {
    const activeTab = event.detail.index;
    let role = 'all';
    switch (activeTab) {
      case 1:
        role = 'buyer';
        break;
      case 2:
        role = 'seller';
        break;
    }

    this.setData({
      activeTab,
      'queryParams.role': role,
      'queryParams.page': 1,
      orderList: []
    });

    await this.loadOrders(true);
  },

  // 加载订单列表
  async loadOrders(refresh = false) {
    if (this.data.loading && !refresh) return; // 如果正在加载且不是强制刷新，则返回

    this.setData({ loading: true });
    if (refresh) {
      this.setData({ 'queryParams.page': 1, orderList: [] });
    }

    try {
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: `${app.globalData.baseUrl}/api/orders`,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${wx.getStorageSync('token')}`
          },
          data: this.data.queryParams,
          success: resolve,
          fail: reject
        });
      });

      if (res.statusCode === 200 && res.data.success) {
        const { orders, total, totalPages, statusCounts } = res.data.data;

        // 格式化订单数据
        const formattedOrders = orders.map(order => ({
          id: order._id,
          status: order.status,
          createTime: this.formatTime(order.createdAt),
          productImage: order.product.images && order.product.images.length > 0 ? order.product.images[0] : '/images/default-thumb.png',
          productTitle: order.product.title,
          price: order.product.price,
          location: order.meetingInfo?.location,
          time: order.meetingInfo?.time ? this.formatTime(order.meetingInfo.time) : '',
          reason: order.cancelReason,
          review: order.review || null // 确保review字段存在，便于WXML判断
        }));

        this.setData({
          orderList: refresh ? formattedOrders : [...this.data.orderList, ...formattedOrders],
          totalPages,
          statusCounts,
          page: this.data.queryParams.page // 同步一下data中的page，虽然主要用queryParams.page
        });
      } else {
        wx.showToast({
          title: res.data.message || '加载失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('加载订单失败：', error);
      wx.showToast({
        title: '加载订单网络错误',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  // 确认交易完成
  async onConfirmTrade(event) {
    const orderId = event.currentTarget.dataset.id;
    if (!orderId) {
      wx.showToast({
        title: '订单ID不存在',
        icon: 'none'
      });
      return;
    }

    try {
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: `${app.globalData.baseUrl}/api/orders/${orderId}/status`,
          method: 'PUT',
          header: {
            'Authorization': `Bearer ${wx.getStorageSync('token')}`,
            'Content-Type': 'application/json'
          },
          data: {
            status: '已完成'
          },
          success: resolve,
          fail: reject
        });
      });

      if (res.statusCode === 200 && res.data.success) {
        wx.showToast({
          title: '交易完成',
          icon: 'success'
        });
        await this.loadOrders(true);
      }
    } catch (error) {
      console.error('确认交易失败：', error);
      wx.showToast({
        title: '确认交易失败',
        icon: 'none'
      });
    }
  },

  // 取消交易
  async onCancelTrade(event) {
    const orderId = event.currentTarget.dataset.id;

    wx.showModal({
      title: '取消交易',
      content: '确定要取消这笔交易吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            const res = await new Promise((resolve, reject) => {
              wx.request({
                url: `${app.globalData.baseUrl}/api/orders/${orderId}/status`,
                method: 'PUT',
                header: {
                  'Authorization': `Bearer ${wx.getStorageSync('token')}`,
                  'Content-Type': 'application/json'
                },
                data: {
                  status: '已取消',
                  reason: '买家主动取消'
                },
                success: resolve,
                fail: reject
              });
            });

            if (res.statusCode === 200 && res.data.success) {
              wx.showToast({
                title: '已取消交易',
                icon: 'success'
              });
              await this.loadOrders(true);
            }
          } catch (error) {
            console.error('取消交易失败：', error);
            wx.showToast({
              title: '取消交易失败',
              icon: 'none'
            });
          }
        }
      }
    });
  },

  // 查看订单详情
  onViewDetail(event) {
    const orderId = event.currentTarget.dataset.id;
    console.log('跳转到订单详情，订单ID:', orderId);

    if (!orderId) {
      console.error('订单ID不存在');
      return;
    }

    wx.navigateTo({
      url: `/pages/order/detail/detail?id=${orderId}`,
      fail: (err) => {
        console.error('跳转失败:', err);
      }
    });
  },

  // 格式化时间
  formatTime(dateString) {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hour = date.getHours().toString().padStart(2, '0');
    const minute = date.getMinutes().toString().padStart(2, '0');
    return `${year}-${month}-${day} ${hour}:${minute}`;
  },

  // 下拉刷新
  async onPullDownRefresh() {
    await this.loadOrders(true);
    wx.stopPullDownRefresh();
  },

  // 上拉加载更多
  async onReachBottom() {
    if (this.data.queryParams.page < this.data.totalPages) {
      this.setData({
        'queryParams.page': this.data.queryParams.page + 1
      });
      await this.loadOrders();
    }
  },

  // 页面显示时重新计算高度
  onShow() {
    // 页面显示时更新一次数据
    if (this.data.needsRefresh) {
      this.loadOrders(true); // 强制刷新列表
      this.setData({ needsRefresh: false }); // 重置标记
    } else if (this.data.orderList.length === 0 && !this.data.loading) {
      // 如果列表为空且不在加载中（例如首次进入页面），则加载
      this.loadOrders(true);
    }
  },

  // 页面尺寸变化时重新计算高度
  onResize() {
    const systemInfo = wx.getSystemInfoSync();
    this.setData({
      windowHeight: systemInfo.windowHeight
    });
  },

  // 按钮点击阻止冒泡
  onButtonTap(e) {
    // 小程序中使用 e.preventDefault() 来阻止事件冒泡
    if (e && e.preventDefault) {
      e.preventDefault();
    }
  },

  goToReview(event) {
    const { id, title, image } = event.currentTarget.dataset;
    if (!id) {
      wx.showToast({
        title: '订单信息错误',
        icon: 'none'
      });
      return;
    }
    wx.navigateTo({
      url: `/pages/review/add/add?orderId=${id}&productTitle=${encodeURIComponent(title || '')}&productImage=${encodeURIComponent(image || '')}`,
    });
  }
}); 